import { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
import { UserService } from '../services/UserService';

interface GetUsersQuery {
  page?: string;
  limit?: string;
}

interface GetUserParams {
  id: string;
}

export default async function userRoutes(fastify: FastifyInstance) {
  const userService = new UserService();

  // 获取用户列表
  fastify.get<{
    Querystring: GetUsersQuery;
  }>('/users', {
    schema: {
      description: '获取用户列表',
      tags: ['用户'],
      querystring: {
        type: 'object',
        properties: {
          page: { type: 'string', default: '1' },
          limit: { type: 'string', default: '10' },
        },
      },
      response: {
        200: {
          type: 'object',
          properties: {
            success: { type: 'boolean' },
            data: {
              type: 'object',
              properties: {
                users: {
                  type: 'array',
                  items: {
                    type: 'object',
                    properties: {
                      id: { type: 'number' },
                      email: { type: 'string' },
                      username: { type: 'string' },
                      phone: { type: 'string' },
                      avatar: { type: 'string' },
                      role: { type: 'string' },
                      isActive: { type: 'boolean' },
                      createdAt: { type: 'string' },
                      updatedAt: { type: 'string' },
                    },
                  },
                },
                total: { type: 'number' },
                page: { type: 'number' },
                limit: { type: 'number' },
              },
            },
          },
        },
      },
    },
  }, async (request: FastifyRequest<{ Querystring: GetUsersQuery }>, reply: FastifyReply) => {
    try {
      const page = parseInt(request.query.page || '1', 10);
      const limit = parseInt(request.query.limit || '10', 10);

      const { users, total } = await userService.findAll(page, limit);

      return reply.send({
        success: true,
        data: {
          users: users.map(user => user.toJSON()),
          total,
          page,
          limit,
        },
      });
    } catch (error) {
      fastify.log.error(error);
      return reply.status(500).send({
        success: false,
        message: '服务器内部错误',
      });
    }
  });

  // 获取单个用户
  fastify.get<{
    Params: GetUserParams;
  }>('/users/:id', {
    schema: {
      description: '获取用户详情',
      tags: ['用户'],
      params: {
        type: 'object',
        required: ['id'],
        properties: {
          id: { type: 'string' },
        },
      },
      response: {
        200: {
          type: 'object',
          properties: {
            success: { type: 'boolean' },
            data: {
              type: 'object',
              properties: {
                user: {
                  type: 'object',
                  properties: {
                    id: { type: 'number' },
                    email: { type: 'string' },
                    username: { type: 'string' },
                    phone: { type: 'string' },
                    avatar: { type: 'string' },
                    role: { type: 'string' },
                    isActive: { type: 'boolean' },
                    createdAt: { type: 'string' },
                    updatedAt: { type: 'string' },
                  },
                },
              },
            },
          },
        },
        404: {
          type: 'object',
          properties: {
            success: { type: 'boolean' },
            message: { type: 'string' },
          },
        },
      },
    },
  }, async (request: FastifyRequest<{ Params: GetUserParams }>, reply: FastifyReply) => {
    try {
      const userId = parseInt(request.params.id, 10);

      if (isNaN(userId)) {
        return reply.status(400).send({
          success: false,
          message: '无效的用户ID',
        });
      }

      const user = await userService.findById(userId);

      if (!user) {
        return reply.status(404).send({
          success: false,
          message: '用户不存在',
        });
      }

      return reply.send({
        success: true,
        data: {
          user: user.toJSON(),
        },
      });
    } catch (error) {
      fastify.log.error(error);
      return reply.status(500).send({
        success: false,
        message: '服务器内部错误',
      });
    }
  });
}